// @/router/dynamic.ts
import router from '@/router'
import { ElLoading } from "element-plus";
import { routerArray } from "./index.ts"
import { StoreUsers } from "@/stores"
import { getUserInfo } from "@/api/authorityApi/authorityApi.js"
import {rou} from './index.ts'

/**
 * 注册路由
 * 用户切换账号需移除 sessionStorage 中的 routerMap 数据
 */
export const registerRoutes = () => {
    // const routerMap = localStorage.getItem("routerMap");
    let routerMap = JSON.parse(localStorage.getItem("permissionList"))
    return new Promise((resolve, reject) => {
        if (routerMap) {
            // addRoutes(routerMap);
            addRoutes(rou[0].children, "");
            resolve(true);
        } else {
            // 获取用户权限
            // const loading = ElLoading.service()
            getUserInfo().then((res) => {
                let result = routerArray.filter((item) => res.data.roles.menus.includes(item.name));
                localStorage.setItem("routerMap", JSON.stringify(result))
                addRoutes(rou[0].children, "");
                resolve(true);
            })
        }
    })
}

/**
 * 动态添加路由
 */
const addRoutes = (routes, parentName = "") => {
    routes.forEach((item) => {
        if (item.path && item.component) {
            item.toString()
            // let componentString = item.component.replace(/^\/+/, ""), // 过滤字符串前面所有 '/' 字符
            // componentPath = componentString.replace(/\.\w+$/, ""); // 过滤掉后缀名，为了让 import 加入 .vue ，不然会有警告提示...
            const route = {
                path: item.path,
                redirect: item.redirect,
                name: item.name,
                component: item.component,
                meta: item.meta
            }
            parentName ? router.addRoute(parentName, route) : router.addRoute(route);
            if (item.children && item.children.length) {
                addRoutes(item.children, item.name);
            }
        }
    })
};

/**
 * 生成管理菜单
 */
export const getAuthMenu = () => {
    // 这里就根据路由生成后台左侧菜单
    const routerMap = localStorage.setItem("routerMap");
    // localStorage.setItem("routerArr", JSON.stringify(routerLo))
}